/* global React */
// Round Builder — "fluid within rails". Strategy stays LOCKED; drivers freely set
// TWO independent options — the Sprint car pool and the Feature car — plus the shared
// track and lap count. Every choice is validated against the guardrails before it
// hits the ballot.
function RoundBuilderScreen() {
  const { Card, Select, Button, Badge, RangeMeter, VoteOption } = window.GT7LeagueDesignSystem_258437;
  const D = window.GT7DATA;
  const R = D.rails;

  const [track, setTrack] = React.useState(D.tracks[2].name);

  // --- Sprint option (broader pool of similar-performance cars) ---
  const [sKlass, setSKlass] = React.useState('Road');
  const [sMin, setSMin] = React.useState(580);
  const [sMax, setSMax] = React.useState(620);
  const [pool, setPool] = React.useState(['Porsche Cayman GT4 \u201916', 'Toyota Supra RZ \u201997', 'BMW M4 \u201914']);

  // --- Feature option (a specific car + laps) ---
  const [fKlass, setFKlass] = React.useState('Road');
  const [fMin, setFMin] = React.useState(580);
  const [fMax, setFMax] = React.useState(620);
  const [featureCar, setFeatureCar] = React.useState('Porsche Cayman GT4 \u201916');
  const [laps, setLaps] = React.useState(18);

  const [ballot, setBallot] = React.useState([]);
  const [fedFrom, setFedFrom] = React.useState(null);

  // Auto-feed from the vote: winning sprint pool + feature car pre-fill this round.
  React.useEffect(() => {
    const apply = () => {
      const v = window.GT7VOTE || {};
      if (v.sprint && v.sprint.build) { const b = v.sprint.build; setSKlass(b.klass); setSMin(b.min); setSMax(b.max); setPool(b.pool); }
      if (v.feature && v.feature.build) { const b = v.feature.build; setTrack(b.track); setFKlass(b.klass); setFMin(b.min); setFMax(b.max); setFeatureCar(b.car); setLaps(b.laps); }
      if (v.sprint || v.feature) setFedFrom({ sprint: v.sprint && v.sprint.label, feature: v.feature && v.feature.label });
    };
    apply();
    window.addEventListener('gt7-vote', apply);
    return () => window.removeEventListener('gt7-vote', apply);
  }, []); // eslint-disable-line

  const sGr = sKlass !== 'Road';
  const fGr = fKlass !== 'Road';
  const trackObj = D.tracks.find(t => t.name === track);
  const lapTimeSec = trackObj ? trackObj.km * 30 : 100;
  const estMin = Math.round((laps * lapTimeSec) / 60);
  const timeOk = estMin >= R.featureTimeTarget.min && estMin <= R.featureTimeTarget.max;
  const autoLaps = () => setLaps(Math.max(1, Math.round((27.5 * 60) / lapTimeSec)));

  const sprintEligible = D.carPool.filter(c => c.klass === sKlass && (sGr || (c.pp >= sMin && c.pp <= sMax)));
  const featureEligible = D.carPool.filter(c => c.klass === fKlass && (fGr || (c.pp >= fMin && c.pp <= fMax)));
  const inPool = sprintEligible.filter(c => pool.includes(c.name));
  const avgPP = inPool.length ? Math.round(inPool.reduce((a, c) => a + c.pp, 0) / inPool.length) : sMin;
  const togglePool = (name) => setPool(p => p.includes(name) ? p.filter(n => n !== name) : [...p, name]);

  // keep feature car valid within the feature window
  React.useEffect(() => {
    if (!featureEligible.some(c => c.name === featureCar)) setFeatureCar(featureEligible[0] ? featureEligible[0].name : '');
  }, [fKlass, fMin, fMax]); // eslint-disable-line

  const issues = [];
  if (!track) issues.push('Pick a track');
  if (inPool.length < 3) issues.push('Sprint pool needs 3+ cars');
  if (!featureCar) issues.push('Choose a feature car (widen the feature window if empty)');
  if (!timeOk) issues.push(`Feature time ${estMin} min — target ${R.featureTimeTarget.min}–${R.featureTimeTarget.max}`);
  const valid = issues.length === 0;

  const submit = () => {
    if (!valid) return;
    setBallot(b => [...b, {
      id: 'b' + Date.now(),
      title: track,
      meta: `Sprint: ${sKlass}${sGr ? ' BoP' : ` ${sMin}–${sMax}`} · ${inPool.length} cars  |  Feature: ${featureCar} · ${laps} laps (~${estMin} min)`,
      votes: 0,
    }]);
  };

  return (
    <div>
      <PageTitle eyebrow="Propose Round 6 · open" title="Round Builder"
        note="Set two options — the Sprint car pool and the Feature car — on a shared track. The guardrails referee every choice." />

      <div style={{ display: 'grid', gridTemplateColumns: '300px 1fr', gap: 20, alignItems: 'start' }}>
        {/* LOCKED RAILS */}
        <Card accent="brand">
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
            <span style={{ fontFamily: 'var(--font-display)', fontSize: 12, letterSpacing: '.13em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>Locked strategy</span>
            <Badge tone="danger">Fixed</Badge>
          </div>
          <RailGroup label="Sprint (Race 1)" items={R.sprint} tone="neutral" />
          <RailGroup label="Feature (Race 2)" items={R.feature} tone="neutral" />
          <RailGroup label="Every round" items={R.global} tone="caution" />
        </Card>

        {/* FLUID CHOICES */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {fedFrom && (
            <Card accent="green">
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
                <Badge tone="positive" solid>From the vote</Badge>
                <span style={{ fontSize: 13.5, color: 'var(--text-body)' }}>Pre-filled the winning options — Sprint: <strong style={{ color: 'var(--text-strong)' }}>{fedFrom.sprint || '—'}</strong> · Feature: <strong style={{ color: 'var(--text-strong)' }}>{fedFrom.feature || '—'}</strong>. Adjust anything below before submitting.</span>
              </div>
            </Card>
          )}
          {/* Shared track */}
          <Card>
            <FieldLabel>Track <span style={{ color: 'var(--text-faint)', fontWeight: 400, textTransform: 'none', letterSpacing: 0 }}>— shared by both races</span></FieldLabel>
            <div style={{ maxWidth: 340 }}>
              <Select options={D.tracks.map(t => t.name)} value={track} onChange={e => setTrack(e.target.value)} />
            </div>
          </Card>

          {/* SPRINT OPTION */}
          <Card accent="cyan">
            <SectionTag n="1" label="Sprint option" hint="Broad pool of similar-performance cars" />
            <ClassWindow klass={sKlass} setKlass={setSKlass} min={sMin} setMin={setSMin} max={sMax} setMax={setSMax} avgPP={avgPP} />
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 18 }}>
              <FieldLabel>Car pool <span style={{ color: 'var(--text-faint)', fontWeight: 400, textTransform: 'none', letterSpacing: 0 }}>— tick the cars allowed</span></FieldLabel>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: inPool.length >= 3 ? 'var(--green-400)' : 'var(--amber-400)' }}>{inPool.length} selected</span>
            </div>
            <CarChecklist eligible={sprintEligible} pool={pool} toggle={togglePool} />
          </Card>

          {/* FEATURE OPTION */}
          <Card accent="gold">
            <SectionTag n="2" label="Feature option" hint="One specific car + lap count" />
            <ClassWindow klass={fKlass} setKlass={setFKlass} min={fMin} setMin={setFMin} max={fMax} setMax={setFMax} />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 18 }}>
              <div>
                <FieldLabel>Feature car</FieldLabel>
                <Select options={featureEligible.length ? featureEligible.map(c => c.name) : ['—']} value={featureCar} onChange={e => setFeatureCar(e.target.value)} />
              </div>
              <div>
                <FieldLabel>Feature laps</FieldLabel>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <Stepper value={laps} set={setLaps} lo={1} hi={60} />
                  <Button variant="ghost" size="sm" onClick={autoLaps}>Auto</Button>
                </div>
              </div>
            </div>
            <div style={{ marginTop: 16, maxWidth: 440 }}>
              <RangeMeter label="Est. feature time" value={estMin} min={R.featureTimeTarget.min} max={R.featureTimeTarget.max} floor={10} ceil={40} unit=" min" />
            </div>
          </Card>

          {/* Validation + submit */}
          <Card accent={valid ? 'green' : 'brand'}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {valid ? (
                  <span style={{ display: 'flex', alignItems: 'center', gap: 8, color: 'var(--green-400)', fontWeight: 600 }}><Badge tone="positive" solid>OK</Badge> Both options within strategy — ready for the ballot</span>
                ) : (
                  <>
                    <span style={{ color: 'var(--amber-400)', fontWeight: 600, fontSize: 13, textTransform: 'uppercase', letterSpacing: '.1em', fontFamily: 'var(--font-display)' }}>Fix before submitting</span>
                    <ul style={{ margin: 0, paddingLeft: 18, fontSize: 13, color: 'var(--text-muted)' }}>
                      {issues.map((x, i) => <li key={i}>{x}</li>)}
                    </ul>
                  </>
                )}
              </div>
              <Button variant="data" disabled={!valid} onClick={submit}>Submit to ballot</Button>
            </div>
          </Card>

          {ballot.length > 0 && (
            <div>
              <FieldLabel>On the ballot ({ballot.length})</FieldLabel>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 10 }}>
                {ballot.map(b => <VoteOption key={b.id} title={b.title} meta={b.meta} votes={b.votes} totalVotes={1} />)}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function ClassWindow({ klass, setKlass, min, setMin, max, setMax, avgPP }) {
  const { Badge, RangeMeter } = window.GT7LeagueDesignSystem_258437;
  const isGr = klass !== 'Road';
  return (
    <div>
      <FieldLabel>Class</FieldLabel>
      <Segmented options={['Road', 'Gr.4', 'Gr.3']} value={klass} onChange={setKlass} />
      <div style={{ marginTop: 18 }}>
        <FieldLabel>Performance window</FieldLabel>
        {isGr ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <Badge tone="caution">BoP on</Badge>
            <span style={{ fontSize: 13, color: 'var(--text-faint)' }}>Balance of Performance equalizes the field — no PP tuning.</span>
          </div>
        ) : (
          <div style={{ display: 'flex', gap: 24, alignItems: 'center', flexWrap: 'wrap' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ fontSize: 12, color: 'var(--text-faint)' }}>Min</span><Stepper value={min} set={v => setMin(Math.min(v, max - 10))} step={5} lo={400} hi={700} /></div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ fontSize: 12, color: 'var(--text-faint)' }}>Max</span><Stepper value={max} set={v => setMax(Math.max(v, min + 10))} step={5} lo={410} hi={720} /></div>
            {avgPP != null && (
              <div style={{ flex: 1, minWidth: 220 }}>
                <RangeMeter label="Pool average" value={avgPP} min={min} max={max} floor={450} ceil={720} unit=" PP" />
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

function CarChecklist({ eligible, pool, toggle }) {
  if (eligible.length === 0) return <p style={{ fontSize: 13, color: 'var(--amber-400)', margin: '8px 0 0' }}>No cars fit this window. Widen the PP range.</p>;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8, marginTop: 12 }}>
      {eligible.map(c => {
        const on = pool.includes(c.name);
        return (
          <button key={c.name} onClick={() => toggle(c.name)} style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8,
            padding: '9px 12px', cursor: 'pointer', textAlign: 'left',
            background: on ? 'rgba(23,198,232,0.08)' : 'var(--surface-raised)',
            border: `1px solid ${on ? 'var(--accent)' : 'var(--border-subtle)'}`,
            borderRadius: 'var(--radius-sm)',
          }}>
            <span style={{ fontSize: 13.5, color: 'var(--text-body)' }}>{c.name}</span>
            <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-faint)' }}>{c.pp}</span>
              <span style={{ width: 16, height: 16, borderRadius: 3, border: `2px solid ${on ? 'var(--accent)' : 'var(--border-strong)'}`, background: on ? 'var(--accent)' : 'transparent', color: '#04252b', fontSize: 11, fontWeight: 700, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>{on ? '\u2713' : ''}</span>
            </span>
          </button>
        );
      })}
    </div>
  );
}

function SectionTag({ n, label, hint }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
      <span style={{ width: 24, height: 24, borderRadius: 'var(--radius-xs)', background: 'var(--surface-raised)', border: '1px solid var(--border-strong)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 12, color: 'var(--text-strong)' }}>{n}</span>
      <span style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 700, letterSpacing: '.04em', textTransform: 'uppercase', color: 'var(--text-strong)' }}>{label}</span>
      <span style={{ fontSize: 12.5, color: 'var(--text-faint)' }}>· {hint}</span>
    </div>
  );
}
function Stepper({ value, set, step = 1, lo, hi }) {
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', border: '1px solid var(--border-strong)', borderRadius: 'var(--radius-sm)', overflow: 'hidden' }}>
      <StepBtn onClick={() => set(Math.max(lo, value - step))}>–</StepBtn>
      <span style={{ minWidth: 52, textAlign: 'center', fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--text-strong)' }}>{value}</span>
      <StepBtn onClick={() => set(Math.min(hi, value + step))}>+</StepBtn>
    </div>
  );
}
function StepBtn({ children, onClick }) {
  return <button onClick={onClick} style={{ width: 30, height: 34, border: 'none', background: 'var(--surface-raised)', color: 'var(--text-strong)', fontSize: 16, cursor: 'pointer', fontFamily: 'var(--font-mono)' }}>{children}</button>;
}
function FieldLabel({ children }) {
  return <div style={{ fontFamily: 'var(--font-display)', fontSize: 11, fontWeight: 600, letterSpacing: '.13em', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: 10 }}>{children}</div>;
}
function RailGroup({ label, items, tone }) {
  const { Badge } = window.GT7LeagueDesignSystem_258437;
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ fontSize: 10.5, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--text-faint)', marginBottom: 7, fontFamily: 'var(--font-display)' }}>{label}</div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
        {items.map((x, i) => <Badge key={i} tone={tone}>{x}</Badge>)}
      </div>
    </div>
  );
}
function Segmented({ options, value, onChange }) {
  return (
    <div style={{ display: 'inline-flex', background: 'var(--ink-900)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-sm)', padding: 3, gap: 3 }}>
      {options.map(o => {
        const on = o === value;
        return (
          <button key={o} onClick={() => onChange(o)} style={{
            padding: '7px 16px', border: 'none', cursor: 'pointer', borderRadius: 'var(--radius-xs)',
            fontFamily: 'var(--font-display)', fontSize: 12, fontWeight: 600, letterSpacing: '.08em', textTransform: 'uppercase',
            background: on ? 'var(--brand)' : 'transparent', color: on ? '#fff' : 'var(--text-faint)',
            transition: 'background 120ms',
          }}>{o}</button>
        );
      })}
    </div>
  );
}
window.RoundBuilderScreen = RoundBuilderScreen;
